﻿var map;
var myLocation;
var mid = 1;
var infoWindow;
var geocoder;
var markersArray = [];



var headHTML = '<div>' +
        '<table style="width: 300px; height: 27px;">' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Service: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<select ID="List" style="width: 90%">' +
			        '<option value="0">Trường Học</option>' +
			        '<option value="1">Bệnh Viện</option>' +
			        '<option value="2">Nhà Sách</option>' +
			        '<option value="3">Địa Điểm Ăn Uống</option>' +
			        '<option value="4">Nhà Thờ</option>' +
			        '<option value="5">Khác</option>' +
                    '</select>' +
                '</td>' +
            '</tr>' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Point Name: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<input name="Name" ID="PointName" type="text" style="width: 90%"/>' +
                '</td>' +
            '</tr>' +
        '</table>' +
    '</div>';


//thêm 2 link thêm, xóa infowindow của 1 nút. tiện cho việc xóa sửa

var tailHTML = '<div>' +
        '<table style="width: 300px; height: 27px;">' +
            '<tr>' +
                '<td class="style1" style="width: 20%" align="center">' +
                    '<a href="#" onclick="AddPoint();">Save</a>' +
                '</td>' +
                '<td class="style1" style="width: 20%" align="center">' +
                    '<a href="#" onclick="DelPoint();">Delete</a>' +
                '</td>' +
                '<td class="style1" style="width: 20%" align="center">' +
                     '<a href="#" onclick="UpdatePoint();">Update</a>' +
                '</td>' +
                '<td class="style1" style="width: 40%" align="certer">' +
                    '<a href="#" id="SearchNearby" onclick="SearchNearby();">Search Nearby</a>' +
                '</td>' +
            '</tr>' +
        '</table>' +
    '</div>';



//hàm thêm point vào cơ sở dữ liệu
function AddPoint() {
    var text = document.getElementById('Lat').value;
    alert(text);
}

// hàm xóa point khỏi csdl
function DelPoint() {
    //them code vao
}

// Hàm update point...
function UpdatePoint()
{ }

//tìm dịch vụ gần với point hiện tại
function SearchNearby() {

}

function initialize() {
    geocoder = new google.maps.Geocoder();

    var myOptions = {
        zoom: 17,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map_canvas'),
            myOptions);



    // Try HTML5 geolocation
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            myLocation = new google.maps.LatLng(position.coords.latitude,
                                             position.coords.longitude);

            map.setCenter(myLocation);
        }, function () {
            handleNoGeolocation(true);
        });
    } else {
        // Browser doesn't support Geolocation
        handleNoGeolocation(false);
    }

    var homeControlDiv = document.createElement('DIV');
    var homeControl = new HomeControl(homeControlDiv, map);

    homeControlDiv.index = 1;
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(homeControlDiv);

    google.maps.event.addListener(map, 'click', function (event) {
        addMarker(event.latLng);
    });
}



function clearOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
    }
}

// Shows any overlays currently in the array
function showOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(map);
        }
    }
}



//them marker vao ban do
function addMarker(location) {
    //tạm thời ẩn các marker khác khi tạo marker mới
    clearOverlays();
    marker = new google.maps.Marker({
        position: location,
        map: map,
        draggable: true,
        animation: google.maps.Animation.DROP
    });

    markersArray.push(marker);
    //    map.setCenter(location);
    for (i in markersArray) {
        google.maps.event.addListener(markersArray[i], 'click', function () {
            ShowInfoWindow(markersArray[i]);
        });

        google.maps.event.addListener(markersArray[i], 'rightclick', function () {
            ShowEditWindow(markersArray[i]);
        });
    }
}



//hàm show thông tin marker
function ShowInfoWindow(marker) {
    infowindow = new google.maps.InfoWindow({
        content: '<div>' +
        '<table style="width: 300px; height: 27px;">' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Latitude: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<label>' + marker.getPosition().lat() + '</label>' +
                '</td>' +
            '</tr>' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Longitude: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<label>' + marker.getPosition().lng() + '</label>' +
                '</td>' +
            '</tr>' +
        '</table>' +
    '</div>'
    });

    infowindow.open(map, marker);
}



//hàm show edit window cho việc thêm xóa marker trên csdl
function ShowEditWindow(marker) {
    var infowindow = new google.maps.InfoWindow({
        content: headHTML +
        '<div>' +
        '<table style="width: 300px; height: 27px;">' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Latitude: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<input type="text" style="width: 90%" Id="Lat" value="' + marker.getPosition().lat() + '"  />' +
                '</td>' +
            '</tr>' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Longitude: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<input type="text" style="width: 90%" Id="Lng" value="' + marker.getPosition().lng() + '"  />' +
                '</td>' +
            '</tr>' +
        '</table>' +
    '</div>' + tailHTML
    });
    infowindow.open(map, marker);
}




//ham xu ly su kien link click
function linkDiaDiem_Click(link) {
    var DiaDiem = link.name;
    Search(DiaDiem, false);
}





//hàm xữ lý sự kiện click vào nút search
function btnDiaDiem_Click() {
    var address = document.getElementById("address").value;
    Search(address, true);
}

//btnChangeManage_Click()...

//Hàm xử lý sự kiện click vào nút Manage Point...
function btnManage_Click() {
    var panel = document.getElementById('diadiempanel');
    var panelContent = "<strong>List Point: </strong></br>" +
    '<div>' +
        '<table style="width: 100%; height: 27px;">' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Service: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<select ID="List" style="width: 90%" onchange="">' +
			        '<option value="0">Trường Học</option>' +
			        '<option value="1">Bệnh Viện</option>' +
			        '<option value="2">Nhà Sách</option>' +
			        '<option value="3">Địa Điểm Ăn Uống</option>' +
			        '<option value="4">Nhà Thờ</option>' +
			        '<option value="5">Khác</option>' +
                    '</select>' +
                '</td>' +
            '</tr>' +
        '</table>' +
    '</div>';

    panel.innerHTML = panelContent;
}



//--------hàm search
function Search(address, flag) {
    clearOverlays();
    if (!geocoder) {
        geocoder = new google.maps.Geocoder();
    }
    var geocoderRequest = { address: address };
    geocoder.geocode(geocoderRequest, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });

            google.maps.event.addListener(marker, 'click', function () {
                ShowInfoWindow(marker);
            });

            google.maps.event.addListener(marker, 'rightclick', function () {
                ShowEditWindow(marker);
            });


            if (flag == true) {
                var panel = document.getElementById('diadiempanel');
                var panelContent = "<strong>Search Results</strong></br>";
                for (var i = 0; i < results.length; i++) {
                    panelContent += '<img id="marker" alt="My Google Map" src="PIC/marker_sprite.png" /><a href="javascript:void(0);" name="' + results[i].formatted_address +
                    '" onclick="linkDiaDiem_Click(this);">' + results[i].formatted_address + '</a>' + '</br></br>';
                }
                panel.innerHTML = panelContent;
            }

        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

//hàm kiểm tra tương thích của trình duyệt
function handleNoGeolocation(errorFlag) {
    if (errorFlag) {
        var content = 'Error: The Geolocation service failed.';
    } else {
        var content = 'Error: Your browser doesn\'t support geolocation.';
    }

    var options = {
        map: map,
        position: new google.maps.LatLng(60, 105),
        content: content
    };

    var infowindow = new google.maps.InfoWindow(options);
    map.setCenter(options.position);
}


/**
* The HomeControl adds a control to the map that simply
* returns the user to Chicago. This constructor takes
* the control DIV as an argument.
*/

function HomeControl(controlDiv, map) {

    // Set CSS styles for the DIV containing the control
    // Setting padding to 5 px will offset the control
    // from the edge of the map
    controlDiv.style.padding = '5px';

    // Set CSS for the control border
    var controlUI = document.createElement('DIV');
    controlUI.style.backgroundColor = 'white';
    controlUI.style.borderStyle = 'solid';
    controlUI.style.borderWidth = '2px';
    controlUI.style.cursor = 'pointer';
    controlUI.style.textAlign = 'center';
    controlUI.title = 'Click to set the map to Home';
    controlDiv.appendChild(controlUI);

    // Set CSS for the control interior
    var controlText = document.createElement('DIV');
    controlText.style.fontFamily = 'Arial,sans-serif';
    controlText.style.fontSize = '12px';
    controlText.style.paddingLeft = '4px';
    controlText.style.paddingRight = '4px';
    controlText.innerHTML = 'Home';
    controlUI.appendChild(controlText);

    // Setup the click event listeners: simply set the map to Chicago
    google.maps.event.addDomListener(controlUI, 'click', function () {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                myLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                map.setCenter(myLocation);
            });
        }
    });
    google.maps.event.addDomListener(window, 'load', initialize);
}


// Các hàm liên quan đến tài khoản...
// Đăng nhập...
function btnLogin_Click() {
    var user = document.getElementById("text_user").value;
    var pass = document.getElementById("text_pass").value;
    if (user == "") {
        alert("Ban chua nhap user!...");
        temp = 0;
    }
    else {
        if (pass == "") {
            alert("Ban chua nhap pass!...");
            temp = 0;
        }
        else {
            // Viết hàm đăng nhập...
            alert("Ban da dang nhap!...");
        }
    }
}


// Đăng xuất...
function btnLogout_Click() {
    alert("Đăng xuất...");
}

// Đăng ký...
function btnRegister_Click() {
    myWindow = window.open('', '', 'width=400,height=250');
    myWindow.document.write('<head runat="server">' +
    '<title>Đăng Ký Tài Khoản</title>' +
    '<script src="Scripts/mapsextend.js" type="text/javascript"></script>' +
'</head>' +
'<body>' +
    '<table style="width:300px;">' +
        '<tr>' +
            '<td colspan="2" align="center">' +
                'ĐĂNG KÝ TÀI KHOẢN&nbsp;</td>' +
        '</tr>' +
        '<tr>' +
            '<td align="right" style="width: 40%">' +
                '<Label ID="Label1">Username: </Label>' +
            '</td>' +
            '<td style="width: 60%">' +
                '<input id="txt_user" type="text" align="left" />' +
            '</td>' +
        '</tr>' +
        '<tr>' +
            '<td align="right" style="width: 40%">' +
                '<Label ID="Label2">Password: </Label>' +
            '</td>' +
            '<td style="width: 60%">' +
                '<input id="txt_pass" type="text" />' +
            '</td>' +
        '</tr>' +
        '<tr>' +
            '<td align="center" colspan="2">' +
                '<input id="Button1" type="button" value="Đăng ký" onclick="btn_DangKy()"/>' +
                    '&nbsp;&nbsp;' +
                '<input id="Button2" type="button" value="Thoát" onclick="btn_Thoat()"/>' +
            '</td>' +
        '</tr>' +
    '</table>' +
    '</body>');
    myWindow.focus();
}

// Hàm xử lý đăng ký...
function btn_DangKy() {
    var user = document.getElementById("txt_user").value;
    var pass = document.getElementById("txt_pass").value;
    if (user == "") {
        alert("Ban chua nhap user!...");
        temp = 0;
    }
    else {
        if (pass == "") {
            alert("Ban chua nhap pass!...");
            temp = 0;
        }
        else {
            // Viết hàm đăng ký tài khoản...
            alert("Ban da dang ky!...");
            window.close();
        }
    }
}

// Hàm xử lý thoát...
function btn_Thoat() {
    alert("Ban da thoat!");
    window.close();
}